package com.example.pool.httpTest;

// 发送同步http请求
// 线程池只有100个线程，发送1000个请求，每个线程要用10次
import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.Logger;
import ch.qos.logback.classic.LoggerContext;
import com.alibaba.fastjson.JSON;
import com.example.pool.httpTest.util.HttpClientUtil;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.slf4j.LoggerFactory;

import java.util.List;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class TestHttpClient {

    static {
        LoggerContext loggerContext = (LoggerContext) LoggerFactory.getILoggerFactory();
        List<Logger> loggerList = loggerContext.getLoggerList();
        loggerList.forEach(logger -> {
            logger.setLevel(Level.INFO);
        });
    }

    public static void main(String[] args) throws Exception {
        int threadCount = 1000;
        int corePoolSize = 10;
        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(corePoolSize, corePoolSize, 2, TimeUnit.SECONDS,
                new ArrayBlockingQueue<>(100), new ThreadPoolExecutor.CallerRunsPolicy());
        CloseableHttpClient httpClient = HttpClientUtil.getHttpClient();
        long startTime = System.currentTimeMillis();
        CountDownLatch latch = new CountDownLatch(threadCount);
        for (int i = 0; i < threadCount; i++) {
            threadPoolExecutor.execute(new MyRunnable(httpClient, i, latch));
        }
        latch.await();
        httpClient.close();
        threadPoolExecutor.shutdown();
        long costTime = System.currentTimeMillis() - startTime;
        System.out.println("总共耗时："+ costTime);
    }

    private static class MyRunnable implements Runnable {
        private CloseableHttpClient httpclient;
        private int i;
        private CountDownLatch latch;

        public MyRunnable(CloseableHttpClient httpclient, int i, CountDownLatch latch) {
            this.httpclient = httpclient;
            this.i = i;
            this.latch = latch;
        }

        @Override
        public void run() {
            try {
                final HttpGet request = new HttpGet("http://localhost:8080/get");
                System.out.println("发送请求" + i);
                HttpResponse response = httpclient.execute(request);
                System.out.println(response.getStatusLine());
                System.out.println("发送请求" + i + "完成");
                latch.countDown();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}